
// export const generateUUID = (): string => {
//     if (typeof crypto !== 'undefined' && (crypto as any).randomUUID) {
//         return (crypto as any).randomUUID().replace(/-/g, '');
//     }
//     const bytes = new Uint8Array(16);
//     if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
//         crypto.getRandomValues(bytes);
//     } else {
//         for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
//     }
//     bytes[6] = (bytes[6] & 0x0f) | 0x40;
//     bytes[8] = (bytes[8] & 0x3f) | 0x80;
//     const hex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
//     console.log(hex)
//     return hex;
// }

export const generateUUID = () => {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c: any) =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    ).replace(/-/g, '')
}

// 时间
export const TimeMessage = () => {
    const now = new Date();
    const year = now.getFullYear(); // 获取年份
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份（0-11，需要加1）
    const date = now.getDate().toString().padStart(2, '0'); // 获取日期
    const hours = now.getHours().toString().padStart(2, '0'); // 获取小时
    const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟
    const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒

    const fullDateTime = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
    return fullDateTime
}

// 格式输出
export const LogMessage = (title: any, data = '') => {
    console.log(`====== 【${title}】(${TimeMessage()}): ======`);
    if (data) console.log(data);
}



// 日志

export const writeLog = (type: string, message: string) => {
    try {
        // 添加防重复机制和数据验证
        const logData = {
            type: type?.trim() || "unknown",
            message: message?.trim() || "",
        };

        // if (logData.type && logData.message) {
        //     writeDocument('config.json', logData, "log").catch((error) => {
        //         console.error("写入日志失败:", error);
        //     });
        // }
        // 确保数据完整性
        if (logData.type && logData.message) {
            // 本地日志存储
            const timestamp = new Date().toISOString();
            const logEntry = {
                timestamp,
                ...logData
            };

            try {
                // 获取现有日志
                const existingLogs = localStorage.getItem('digitalHuman_logs') || '[]';
                const logs = JSON.parse(existingLogs);

                // 添加新日志条目
                logs.push(logEntry);

                // 限制日志数量，保留最近100条
                if (logs.length > 100) {
                    logs.splice(0, logs.length - 100);
                }

                // 保存到本地存储
                localStorage.setItem('digitalHuman_logs', JSON.stringify(logs));

                // 同时在控制台输出
                console.log(`[${timestamp}] ${logData.type}: ${logData.message}`);
            } catch (error) {
                console.error("本地日志存储失败:", error);
            }
        }
    } catch (error) {
        console.error("创建日志数据失败:", error);
    }
};


// 自动启动WebSocket相关功能
export interface AutoStartConfig {
    onAutoStart: () => Promise<void>;
    onError?: (error: any) => void;
    isConnected?: () => boolean; // 可选的连接状态检查函数
}

// 计算到下一个9点的毫秒数
export const getTimeUntilNextNineAM = (): number => {
    const now = new Date();
    const nextNineAM = new Date(now);
    nextNineAM.setHours(9, 0, 0, 0);

    // 如果今天已经过了9点，设置为明天的9点
    if (now.getHours() >= 9) {
        nextNineAM.setDate(nextNineAM.getDate() + 1);
    }

    return nextNineAM.getTime() - now.getTime();
};

// 设置每天9点自动启动WebSocket
export const setupAutoStart = (config: AutoStartConfig): (() => void) => {
    let autoStartTimerRef: NodeJS.Timeout | null = null;
    const scheduleNextAutoStart = () => {
        const timeUntilNextNineAM = getTimeUntilNextNineAM();
        // 清除之前的定时器
        if (autoStartTimerRef) clearTimeout(autoStartTimerRef);
        // 设置定时器到下一个9点
        autoStartTimerRef = setTimeout(async () => {
            console.log("自动启动WebSocket连接");
            writeLog("auto", "每天9点自动启动WebSocket");
            // 检查是否已经连接
            if (config.isConnected && config.isConnected()) {
                console.log("WebSocket已经连接，跳过自动启动");
                writeLog("auto", "WebSocket已连接，跳过自动启动");
                // 设置下一个9点的定时器
                scheduleNextAutoStart();
                return;
            }
            try {
                await config.onAutoStart();
                console.log("WebSocket自动启动成功");
            } catch (error) {
                console.error("自动启动WebSocket失败:", error);
                if (config.onError) {
                    config.onError(error);
                }
            }
            // 设置下一个9点的定时器
            scheduleNextAutoStart();
        }, timeUntilNextNineAM);
    };
    // 开始设置自动启动
    scheduleNextAutoStart();
    // 返回清理函数
    return () => {
        if (autoStartTimerRef) {
            clearTimeout(autoStartTimerRef);
            autoStartTimerRef = null;
        }
    };
};


